<?php

namespace app\services;

use app\libs\XSmtp;
use yii;

/**
 * CommonService类
 * @author administrator
 * @since 2017-07-10
 */
class CommonService
{

    /**
     * 校验密码
     * @param $password
     * @return int
     */
    public function passwordValidator($password)
    {
        $score = 0;
        if (preg_match('/[0-9]+/', $password)) {
            $score++;
        }
        if (preg_match('/[a-zA-Z]+/', $password)) {
            $score++;
        }
        if (preg_match("/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]+/", $password)) {
            $score += 2;
        } else {
            $score = 0;
        }
        if (strlen($password) >= 6) {
            $score++;
        } elseif (strlen($password) < 6) {
            $score = 0;
        }
        return $score;
    }

    /**
     * 验证邮箱
     */
    public function email($str)
    {
        if (empty($str)) {
            return true;
        }

        $chars = '/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}$/i';
        if (strpos($str, '@') !== false && strpos($str, '.') !== false) {
            if (preg_match($chars, $str)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 发送邮件方法
     */
    public function sendmailto($mailto, $mailsub, $mailbd, $debug = true)
    {
        //require_once ('email.class.php');
        //##########################################
        $smtpserver     = Yii::$app->params['smtp']['smtpserver']; //SMTP服务器
        $smtpserverport = 25; //SMTP服务器端口
        $smtpusermail   = Yii::$app->params['smtp']['smtpuser']; //SMTP服务器的用户邮箱
        $smtpemailto    = $mailto;
        $smtpuser       = Yii::$app->params['smtp']['smtpuser']; //SMTP服务器的用户帐号
        $smtppass       = Yii::$app->params['smtp']['smtppass'];
        $mailsubject    = $mailsub; //邮件主题
        $mailsubject    = '=?UTF-8?B?' . base64_encode($mailsubject) . '?='; //防止乱码
        $mailbody       = $mailbd; //邮件内容
        //$mailbody = "=?UTF-8?B?".base64_encode($mailbody)."?="; //防止乱码
        $mailtype = 'HTML'; //"HTML"; //邮件格式（HTML/TXT）,TXT为文本邮件. 139邮箱的短信提醒要设置为HTML才正常
        ##########################################
        //var_dump($smtpserver);exit;
        $smtp        = new XSmtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
        $smtp->debug = $debug; //是否显示发送的调试信息
        return $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
    }

    public static function setSession($name, $value)
    {
        Yii::$app->session->set($name, $value);
    }

    public static function removeSession($name)
    {
        Yii::$app->session->remove($name);
    }

    public static function getSession($name)
    {
        $value = Yii::$app->session->get($name);
        return $value ? $value : 0;
    }
}
